package com.example.bit.captchademo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.bit.captchademo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("captcha")
public class CaptchaController {

        //验证码超时时间:10min
        private static final long CAPTCHA_TIME_OUT=10*60*1000;

        @Autowired
        private CaptchaProperties captchaProperties;

        @RequestMapping("getCaptcha")
        public void createCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
                LineCaptcha lineCaptcha= CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());//创建一个验证码
                String code=lineCaptcha.getCode();//获取验证码
                System.out.println("验证码是:"+code);
                session.setAttribute(captchaProperties.getSession().getCode(),code);//设置session
                session.setAttribute(captchaProperties.getSession().getTime(),System.currentTimeMillis());

                response.setContentType("image/png");//设置contentType
                lineCaptcha.write(response.getOutputStream());//写入到输出流
                response.getOutputStream().close();
        }

        @RequestMapping("/check")
        public boolean check(String captcha,HttpSession session){
                //用户传入参数校验
                if(!StringUtils.hasLength(captcha)){
                        return false;
                }

                //获取session中参数
                String captcha_code =(String) session.getAttribute(captchaProperties.getSession().getCode());
                Long captcha_time = (Long) session.getAttribute(captchaProperties.getSession().getTime());


                //参数及超时校验
                if(!StringUtils.hasLength(captcha_code)||captcha_time==null
                        || (System.currentTimeMillis()-captcha_time>CAPTCHA_TIME_OUT)){
                        return false;
                }

                //不区分大小写
                if(captcha.equalsIgnoreCase(captcha_code)){
                        return true;
                }
                return false;
        }

}